import { Context } from '@midwayjs/koa';
import { BillCodeGenerator } from './../service/tool.service';
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Put,
} from '@midwayjs/core';
import { DB } from '../entity/db';
import { Transport, TransportDto4Modify } from '../entity/trasport.entity';
import { MissTargetError } from '../filter/missTarget.filter';

@Controller('/transport')
export class TransportController {
  @Inject()
  dB: DB;
  @Inject()
  billCodeGenerator: BillCodeGenerator;
  @Inject()
  ctx: Context;
  @Get('/query')
  async query(): Promise<Array<Transport>> {
    console.log('query controller ing...');
    // this.ctx.setAttr("xxx","xxxx")
    const ww = this.ctx.getAttr('username');
    console.log('当前用户信息：', ww);
    return this.dB.transports;
  }
  @Post('/insert')
  async insert(@Body() transport: Transport): Promise<Transport> {
    console.log(transport);
    transport.transportId = this.billCodeGenerator.nextCode();
    this.dB.transports.push(transport);
    console.log(this.dB.transports);

    return transport;
  }
  @Del('/remove/:id')
  async remove(@Param('id') id: string): Promise<string> {
    console.log('-------remove----被调用到了');
    const index = this.dB.transports.findIndex(e => e.transportId === id);
    if (index < 0) {
      throw new MissTargetError('删除不对劲');
    }
    this.dB.transports.splice(index, 1);
    return id;
    // if (index !== -1) {
    //   this.dB.transports.splice(index, 1);
    //   return id;
    // } else {
    //   throw new MissTargetError('数据没找到');
    // }
  }
  @Get('/find/:id')
  async find(@Param('id') id: string): Promise<Transport> {
    const tr = this.dB.transports.find(e => e.transportId === id);
    if (!tr) {
      throw new MissTargetError('该' + id + '的数据不存在');
    }

    return tr;
    // if (tr) {
    //   return tr;
    // }
  }
  @Put('/modify')
  async modify(@Body() transport: Transport): Promise<Transport> {
    const index: number = this.dB.transports.findIndex(
      e => e.transportId === transport.transportId
    );
    if (index < 0) {
      throw new MissTargetError('待修改的数据不存在');
    }
    this.dB.transports[index] = transport;
    return transport;
  }
  // 勤劳修改方式 成本一 dto  成本二 复制属性
  @Put('/modify/:id')
  async modifyById(
    @Param('id') id: string,
    @Body() transportDto: TransportDto4Modify
  ): Promise<Transport> {
    const element: Transport = this.dB.transports.find(
      e => e.transportId === id
    );
    Object.assign(element, transportDto);
    // element.ssname = transportDto.xxname;
    // element.reciever = transportDto.reciever;
    return element;
  }
}
